package hui.zhang.web.action.base;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import hui.zhang.domain.base.Courier;
import hui.zhang.service.base.CourierService;

@Controller
@ParentPackage("struts-default")
@Namespace("/")
@Scope("prototype")
@SuppressWarnings("all")
public class CourierAction extends ActionSupport implements ModelDriven<Courier> {

	// 模型驱动
	private Courier courier = new Courier();
	public Courier getModel() {
		return courier;
	}

	// 注入service
	@Autowired
	private CourierService courierService;

	/**
	 * 添加 修改快递员信息
	 * @return
	 */
	@Action(value = "courier_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/courier.html") })
	public String save() {
		courierService.save(courier);
		return SUCCESS;
	}

	// 属性封装分页前台收据
	private Integer page;
	private Integer rows;

	public Integer getPage() {
		return page;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	/**
	 * 分页显示
	 * 改写一次，待条件的分页
	 */
	@Action(value="courier_pageQuery")
	public void findByPage() {
		Pageable pageable = new PageRequest(page-1, rows);
		
		//根据条件查询 构造Specification条件查询对象 类似于QBC
		Specification<Courier> specification = new Specification<Courier>() {
			/**
			 * 构造条件查询方法，如果方法返回null 代表无条件查询
			 * Root 获取条件表达式 name=? age=?
			 * CriteriaQuery 构造简单查询条件返回 提供where方法
			 * CriteriaBuiler 构造Predicate对象，条件查询 构造复杂查询效果
			 */
			public Predicate toPredicate(Root<Courier> root, 
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				//当前查询Root根对象Courier
				List<Predicate> list = new ArrayList<Predicate>();
				if(StringUtils.isNotBlank(courier.getCourierNum())) {
					//进行快递员 工号查询 courierNum=?
					Predicate p1 = cb.equal(root.get("courierNum").as(String.class),courier.getCourierNum());
					list.add(p1);
				}
				if(StringUtils.isNotBlank(courier.getCompany())) {
					//公司模糊查询
					// company like %?%
					Predicate p2 = cb.like(root.get("company").as(String.class),
							"%"+courier.getCompany()+"%");
					list.add(p2);
				}
				if(StringUtils.isNotBlank(courier.getType())) {
					//快递员类型查询
					Predicate p3 = cb.equal(root.get("type").as(String.class),
							courier.getType());
					list.add(p3);
				}
				//多表查询（查询当前对象 关联对象 对应数据表）
				//使用Courier(Root)，关联Standard
				Join<Object, Object> standardRoot = root.join("standard",JoinType.INNER);
				if(courier.getStandard() != null && StringUtils.isNotBlank(
						courier.getStandard().getName())) {
					//进行收派标准 名称 模糊查询
					//standard.name like %?%
					Predicate p4 = cb.like(standardRoot.get("name").
							as(String.class), "%"+courier.getStandard().getName()+"%");
					list.add(p4);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		
		Page<Courier> page = courierService.findByPage(specification,pageable);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("total", page.getTotalElements());
		map.put("rows", page.getContent());
		String jsonString = JSONObject.toJSONString(map);
		try {
			ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
//			System.out.println(jsonString);
			ServletActionContext.getResponse().getWriter().print(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 伪删除
	 */
	@Action(value="courier_delBatch",results={@Result(name="success",
			type="redirect",location="/pages/base/courier.html")})
	public String delBatch() {
		try {
			String ids = ServletActionContext.getRequest().getParameter("ids");
			String[] split = ids.split(",");
			courierService.delBatch(split);
			return SUCCESS;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 恢复快递员状态
	 */
	@Action(value="courier_restore",results={@Result(name="success",
			location="/pages/base/courier.html",type="redirect")})
	public String restore() {
		try {
			String ids = ServletActionContext.getRequest().getParameter("ids");
			String[] split = ids.split(",");
			courierService.restore(split);
			return SUCCESS;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	//查询未关联定区的快递员
	@Action(value="courier_findNoAssociation")
	public String findNoAssociation() {
		List<Courier> list = courierService.findNoAssociation();
		String jsonString = JSONObject.toJSONString(list);
		ServletActionContext.getResponse().setContentType("text/json;charset=utf-8");
		try {
			ServletActionContext.getResponse().getWriter().write(jsonString);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return NONE;
	}

}
